﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Security.Cryptography;

namespace CmpEdu
{
    class UserManager
    {
        //建立数据库的连接
        public static string ConnStr = "Data Source=edp-ir128\\sqlexpress; Initial Catalog=UserManager; Trusted_Connection=true";
        public static SqlConnection Conn = new SqlConnection(ConnStr);
        
        /// <summary>
        /// 登录检查：检查用户名密码是否存在，如果存在返回用户的级别；
        /// 返回string val，1=管理员，0=普通用户，3=不存在。
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static string CheckUser(string name,string pwd)
        {
            string val;     //用于存放返回值
            try
            {
                //以下四段为处理密码
                byte[] TempPwd = Encoding.Default.GetBytes(pwd);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] EncryptPwd = md5.ComputeHash(TempPwd);
                string Md5Pwd = BitConverter.ToString(EncryptPwd).Replace("-", "");

                string SQLStr = "select userlevel from Admin where username = '" + name + "' and userpwd= '" + Md5Pwd + "'";
                SqlCommand cmd = new SqlCommand(SQLStr, Conn);
                //SqlCommand cmd = new SqlCommand(SQLStr, UMConnStr);
                Conn.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                dr.Read();
                if(dr.HasRows)
                {
                    val = dr["userlevel"].ToString();
                }
                else
                {
                    val = "3";        //用户不存在则返回3
                }
            }
            finally
            {
                Conn.Close();
            }
            return val;
        }

        /// <summary>
        /// 注册检查：重载CheckUser方法,检查记录是否存在
        /// 返回bool true or false
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool CheckUser(string name)
        {
            try
            {
                string SQLStr = "select * from Admin where username = '" + name + "'";
                SqlCommand cmd = new SqlCommand(SQLStr, Conn);
                Conn.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr==null)
                {
                    return true;
                }
                dr.Read();
                if (dr.HasRows)
                {
                    return false;       //用户名存在
                }
                else
                {
                    return true;        //用户名不存在
                }
            }
            finally
            {
                Conn.Close();
            }
        }

        /// <summary>
        /// 读出数据流，name, pwd, level
        /// 返回一条信息string msg,用来指示插入的情况
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="level"></param>
        /// <returns></returns>
        public static string AddUser(string name,string pwd,string level)
        {
            string msg;
            if (!CheckUser(name))       //CheckUser=false，完备性检查未通过，姓名重复
            {
                msg = "用户名已经存在，请更换！";
            }
            else
            {
                if (level=="管理员")
                {
                    level = "1";
                }
                else
                {
                    level = "0";
                }                   
                //以下四段为处理密码
                byte[] TempPwd = Encoding.Default.GetBytes(pwd);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] EncryptPwd = md5.ComputeHash(TempPwd);
                string Md5Pwd = BitConverter.ToString(EncryptPwd).Replace("-","");
                try
                {
                    Conn.Open();
                    string InsertSQLStr = "insert into Admin(username,userpwd,userlevel) " +
                        "values('" + name +"', '"+ Md5Pwd + "', '" + level +"')";
                    SqlCommand cmd = new SqlCommand(InsertSQLStr,Conn);
                    cmd.ExecuteNonQuery();
                    msg = "用户添加成功";
                }
                catch (Exception ex)
                {

                    msg = ex.Message;
                }
                finally
                {
                    Conn.Close();
                }
            }
            return msg;
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string DelUser(string name)
        {
            string msg;
            try
            {
                Conn.Open();
                if (name != "admin")
                {
                    string InsertSQLStr = "delete from admin where username = '" + name + "'"; 
                    SqlCommand cmd = new SqlCommand(InsertSQLStr, Conn);
                    cmd.ExecuteNonQuery();
                    msg = "用户删除成功";
                }
                else
                {
                    msg = "默认管理员admin不能删除";
                }
            }
            finally
            {
                Conn.Close();
            }
            return msg;
        }
    }
}
